<template>
  <el-dialog
    :model-value="visible"
    title="商品详情"
    width="700px"
    :before-close="handleCancel"
  >
    <div v-if="good" class="detail-content">
      <!-- 商品图片 -->
      <div class="good-images-detail">
        <el-carousel 
          v-if="displayImages.length > 0" 
          :interval="3000" 
          indicator-position="outside"
          height="300px"
          :loop="true"
          @change="handleCarouselChange"
        >
          <el-carousel-item v-for="(image, index) in displayImages" :key="index">
            <img :src="image" :alt="good.title" class="detail-image" @error="handleImageError" />
          </el-carousel-item>
        </el-carousel>
        <div v-else class="no-image-detail">
          <el-icon size="64"><Picture /></el-icon>
          <span>暂无图片</span>
        </div>
      </div>

      <!-- 商品信息 -->
      <el-descriptions title="商品信息" :column="2" border style="margin-top: 24px">
        <el-descriptions-item label="商品标题" :span="2">
          {{ good.title }}
        </el-descriptions-item>
        <el-descriptions-item label="商品描述" :span="2">
          {{ good.description }}
        </el-descriptions-item>
        <el-descriptions-item label="商品分类">
          <el-tag :type="getCategoryType(good.category)">
            {{ good.category }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="商品价格">
          <span class="detail-price">¥{{ good.price }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="当前状态">
          <el-tag :type="getStatusType(good.status)">
            {{ getStatusText(good.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="发布时间">
          {{ formatTime(good.created_at) }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- 卖家信息 -->
      <el-descriptions title="卖家信息" :column="2" border style="margin-top: 24px">
        <el-descriptions-item label="卖家" :span="2">
          <div class="seller-detail">
            <el-avatar :src="getFullImageUrl(good.seller?.avatar)" :size="32" />
            <span style="margin-left: 8px">{{ good.seller?.nickname || '未知用户' }}</span>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="联系方式">
          {{ good.contact_info }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- 操作按钮 -->
      <div class="action-buttons" style="margin-top: 24px; text-align: center">
        <el-button
          v-if="isMyGood && good.status === 1"
          type="primary"
          @click="handleUpdateStatus(0)"
        >
          下架商品
        </el-button>
        <el-button
          v-if="isMyGood && good.status === 0"
          @click="handleUpdateStatus(1)"
        >
          重新上架
        </el-button>
        <el-button
          v-if="isMyGood && good.status === 1"
          type="success"
          @click="handleUpdateStatus(2)"
          style="margin-left: 8px"
        >
          标记为已售出
        </el-button>
        <el-button
          v-if="isMyGood"
          type="danger"
          @click="handleDelete"
          style="margin-left: 8px"
        >
          删除
        </el-button>
      </div>
    </div>

    <el-skeleton v-else :rows="10" animated />
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Picture } from '@element-plus/icons-vue';
import { goodApi } from '@/api/good';
import { useUserStore } from '@/stores/user';

const userStore = useUserStore();
const props = defineProps({
  visible: Boolean,
  good: Object
});

const emit = defineEmits(['cancel', 'update']);

// 计算是否为当前用户的商品
const isMyGood = computed(() => {
  return props.good?.user_id === userStore.userInfo?.user_id;
});

// 获取完整的图片URL
const getFullImageUrl = (url) => {
  if (!url) return '';
  
  // 如果已经是完整URL，直接返回
  if (url.startsWith('http') || url.startsWith('//') || url.startsWith('blob:')) {
    return url;
  }
  
  // 处理相对路径
  const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:7001';
  
  // 如果是以 /public/ 开头的路径，直接拼接
  if (url.startsWith('/public/')) {
    return `${baseUrl}${url}`;
  }
  
  // 其他情况，直接拼接基础URL
  return url.startsWith('/') ? `${baseUrl}${url}` : `${baseUrl}/${url}`;
};

// 处理图片加载错误
const handleImageError = (event) => {
  console.error('图片加载失败:', event.target.src);
  // 设置一个默认图片
  event.target.src = '';
};

// 处理图片数据
const displayImages = computed(() => {
  if (!props.good?.images) return [];
  
  let imageUrls = [];
  
  // 如果已经是数组，直接返回
  if (Array.isArray(props.good.images)) {
    imageUrls = props.good.images.filter(url => url && url.trim());
  }
  // 如果是字符串，转换为数组
  else if (typeof props.good.images === 'string') {
    // 处理逗号分隔的字符串
    if (props.good.images.includes(',')) {
      imageUrls = props.good.images.split(',').filter(url => url && url.trim());
    }
    // 处理单个URL字符串
    else if (props.good.images.trim()) {
      imageUrls = [props.good.images.trim()];
    }
  }
  
  // 转换为完整URL
  return imageUrls.map(url => getFullImageUrl(url));
});

// 轮播图切换处理
const handleCarouselChange = (currentIndex, prevIndex) => {
  console.log(`详情轮播图从 ${prevIndex} 切换到 ${currentIndex}`);
};

// 分类类型映射
const getCategoryType = (category) => {
  const types = {
    '电子产品': 'primary',
    '学习用品': 'success',
    '生活用品': 'warning',
    '服装鞋帽': 'danger',
    '图书资料': 'info',
    '其他': ''
  };
  return types[category] || '';
};

// 状态类型映射
const getStatusType = (status) => {
  const types = {
    1: 'success',  // 在售
    0: 'warning',  // 已下架
    2: 'info'      // 已售出
  };
  return types[status] || '';
};

// 状态文本映射
const getStatusText = (status) => {
  const texts = {
    1: '在售',
    0: '已下架',
    2: '已售出'
  };
  return texts[status] || '未知状态';
};

// 格式化时间
const formatTime = (time) => {
  if (!time) return '';
  return new Date(time).toLocaleString();
};

// 更新状态
const handleUpdateStatus = async (newStatus) => {
  try {
    const response = await goodApi.updateStatus(props.good.item_id, newStatus);
    if (response.code === 0) {
      ElMessage.success('状态更新成功');
      emit('update');
    } else {
      ElMessage.error(response.msg || '状态更新失败');
    }
  } catch (error) {
    ElMessage.error('网络错误，请重试');
    console.error('更新状态失败:', error);
  }
};

// 删除商品
const handleDelete = () => {
  ElMessageBox.confirm(
    `确定要删除 "${props.good.title}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const response = await goodApi.delete(props.good.item_id);
      if (response.code === 0) {
        ElMessage.success('删除成功');
        emit('update');
      } else {
        ElMessage.error(response.msg || '删除失败');
      }
    } catch (error) {
      ElMessage.error('网络错误，请重试');
      console.error('删除商品失败:', error);
    }
  });
};

// 取消操作
const handleCancel = () => {
  emit('cancel');
};
</script>

<style scoped>
.detail-content {
  padding: 8px;
}

.good-images-detail {
  height: 300px;
  overflow: hidden;
  border-radius: 8px;
}

.detail-image {
  width: 100%;
  height: 300px;
  object-fit: cover;
}

.no-image-detail {
  height: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  color: #999;
  border-radius: 8px;
}

.seller-detail {
  display: flex;
  align-items: center;
}

.detail-price {
  font-size: 18px;
  font-weight: bold;
  color: #ff4d4f;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

:deep(.el-carousel__indicators--outside) {
  bottom: -30px;
}

:deep(.el-descriptions__title) {
  font-size: 16px;
  font-weight: 600;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
}

/* 确保轮播图循环播放样式 */
:deep(.el-carousel) {
  position: relative;
}

:deep(.el-carousel__container) {
  position: relative;
  height: 300px;
}

:deep(.el-carousel__item) {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: inline-block;
  overflow: hidden;
  z-index: 0;
}

:deep(.el-carousel__item.is-active) {
  z-index: 2;
}

:deep(.el-carousel__item.is-animating) {
  transition: transform 0.4s ease-in-out;
}
</style>